package com.jdj.framework.core.base.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * gzip工具类
 *
 * @author caijinbang
 * @date 2019-04-13 15:39
 */
public class GZipUtils {

    /**
     * 日志记录对象
     */
    private static Log log = LogFactory.getLog(GZipUtils.class);

    /**
     * 将源数据压缩
     *
     * @param str 源数据
     * @return 压缩过的数据
     */
    public static byte[] zip(byte[] str) {
        if (str == null) {
            return null;
        }
        ByteArrayOutputStream out = null;
        GZIPOutputStream gzip = null;
        try {
            out = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(out);
            gzip.write(str);
            gzip.finish();
            return out.toByteArray();
        } catch (IOException e) {
            log.error(e);
            return str;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (gzip != null) {
                    gzip.close();
                }
            } catch (IOException e) {
                log.error(e);
            }
        }
    }

    /**
     * 将源数据解压缩
     *
     * @param str 被压缩数据
     * @return 解压缩的数据
     */
    public static byte[] unzip(byte[] str) {
        if (str == null) {
            return null;
        }
        ByteArrayInputStream in = null;
        GZIPInputStream gzip = null;
        ByteArrayOutputStream out = null;
        try {
            in = new ByteArrayInputStream(str);
            gzip = new GZIPInputStream(in);
            int i = gzip.read();
            out = new ByteArrayOutputStream();
            while (i != -1) {
                out.write(i);
                i = gzip.read();
            }
            return out.toByteArray();
        } catch (IOException e) {
            log.error(e);
            return str;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (gzip != null) {
                    gzip.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
}
